package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 账号注册窗体
 */
public class RegistAddressActivity extends RootActivity {

    private ImageView iv_regist_back;
    private EditText et_regist_email_address;
    private EditText et_regist_captcha;
    private TextView tv_regist_next;
    private Button bt_send_code;

    private Message timeMsg;

    private String email_address;
    private String regist_captcha;
    private boolean threadRun;

    /**
     * 主线程修改UI
     */
    private Handler handlerChangeBt = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (threadRun) {
                        if ("0s".equals(msg.obj)) {
                            stopTimeKeepingThread();
                            return;
                        }
                        bt_send_code.setText(msg.obj + "");
                    }
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist_address);

        initView();
        initViewListener();
    }

    /**
     * 初始化组件
     */
    public void initView() {
        iv_regist_back = (ImageView) findViewById(R.id.iv_regist_back);
        bt_send_code = (Button) findViewById(R.id.bt_regist_send_code);
        tv_regist_next = (TextView) findViewById(R.id.tv_regist_next);

        et_regist_email_address = (EditText) findViewById(R.id.et_regist_email_address);
        et_regist_captcha = (EditText) findViewById(R.id.et_regist_captcha);

        timeMsg = new Message();
        threadRun = true;
    }

    /**
     * 组件监听事件添加
     */
    public void initViewListener() {
        //回退按钮事件
        iv_regist_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //编辑字体内容监听
        et_regist_email_address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!"Send code".equals(bt_send_code.getText().toString())) {
                    bt_send_code.setText("Send code");
                    threadRun = false;
                }
                bt_send_code.setEnabled(true);
            }
        });

        //请求获得验证码
        bt_send_code.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //判断是否输入邮箱地址
                if (null == et_regist_email_address.getText() || "".equals(et_regist_email_address.getText().toString())) {
                    Toast.makeText(RegistAddressActivity.this.getApplicationContext(), ToastConstant.INPUT_EMAIL_ADDRESS_FIRST, Toast.LENGTH_SHORT).show();
                    return;
                }
                email_address = et_regist_email_address.getText().toString();
                //请求验证码按钮不可按
                bt_send_code.setEnabled(false);

                //向服务器请求邮箱验证码
                Map<String, String> params_response_code = new HashMap<>();
                params_response_code.put(WebConstant.GET_EMAIL_AUTH_PATH_CHECK, "2");
                new GetJsonFromWebJob(WebConstant.GET_EMAIL_AUTH_PATH + email_address, WebConstant.POST, params_response_code, REQUEST_SIGN_GET_EMAIL_CAPTCHA,RegistAddressActivity.this).start();

                //开启计时线程，修改验证码发送的时机
                threadRun = true;
                new TimeKeepingThread().start();
            }
        });

        //跳转页面之前判断验证码是否符合
        tv_regist_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //判断是否输入验证码
                if (null == et_regist_captcha.getText() || "".equals(et_regist_captcha.getText().toString())) {
                    Toast.makeText(RegistAddressActivity.this.getApplicationContext(), ToastConstant.INPUT_CAPTCHA_FIRST, Toast.LENGTH_SHORT).show();
                    return;
                }
                regist_captcha = et_regist_captcha.getText().toString();

                //判断验证码是否符合
                Map<String, String> params_judge_code = new HashMap<>();
                params_judge_code.put(WebConstant.AUTH_EMAIL_AUTH_PATH_EMAIL, email_address);
                params_judge_code.put(WebConstant.AUTH_EMAIL_AUTH_PATH_CODE, regist_captcha);
                new GetJsonFromWebJob(WebConstant.AUTH_EMAIL_AUTH_PATH, WebConstant.GET, params_judge_code, REQUEST_SIGN_VERIFICATE_EMAIL_CAPTCHA,RegistAddressActivity.this).start();
            }
        });
    }

    /**
     * 处理从网络获取的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        //获取由message传递的数据 并对数据进行处理和解析
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        //判断邮箱已被注册
        if (webResult.contains("user already existed")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.EMAIL_HAS_BEEN_USED, Toast.LENGTH_SHORT).show();
            stopTimeKeepingThread();
            return;
        }
        //判断验证码已过期
        if (webResult.contains("verification code expired")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_EXPIRE, Toast.LENGTH_SHORT).show();
            stopTimeKeepingThread();
            return;
        }
        //判断验证码不匹配
        if (webResult.contains("verification code mismatched")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_MISMATCH, Toast.LENGTH_SHORT).show();
            stopTimeKeepingThread();
            return;
        }
        //后台反馈邮件发送失败 提示用户
        if (webResult.contains("sent failed")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_SEND_FAILED, Toast.LENGTH_LONG).show();
            stopTimeKeepingThread();
            return;
        }

        //验证码验证成功，进行页面跳转
        if (REQUEST_SIGN_VERIFICATE_EMAIL_CAPTCHA == webSign && "".equals(webResult)) {
            //页面跳转
            Map<String, String> params_change_activity = new HashMap<>();
            params_change_activity.put("email_address", email_address);
            params_change_activity.put("captcha", regist_captcha);
            activityChange(REGIST_PASSWORD_ACTIVITY, params_change_activity, null);
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            }catch (Exception e){
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }

    /**
     * 验证码重发计时线程
     */
    class TimeKeepingThread extends Thread {
        @Override
        public void run() {
            for (int i = 60; i >= 0; i--) {
                if (threadRun) {
                    SystemClock.sleep(990);
                    timeMsg.obj = i + "s";
                    handlerChangeBt.handleMessage(timeMsg);
                }
            }
        }
    }

    private void stopTimeKeepingThread(){
        threadRun = false;
        bt_send_code.setEnabled(true);
        bt_send_code.setText("Send code");
    }
}
